import { queryProjectInstDetail, queryOrderInfoDetail, uploadImg, inspectorSaveOrder } from '../../services/order'
import { queryProjectList } from '../../services/project'
import { updateInstInfo } from '../../services/inspect'
import dayjs from 'dayjs'

Page({
  /**
   * 页面的初始数据
   */
  data: {
    orderId:"",
    projectId:"",
    instId:"",
    instInfo:{},
    orderInfo:{},
    defaultPictureUrl:'../../assets/inspect/photo.png',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if(!options){
      return
    }
    let orderId = options.orderId
    let projectId = options.projectId
    let instId = options.instId
    this.setData({
      orderId,
      projectId,
      instId
    })
    this.getProjectInstDetail(instId)
    this.getOrderInfoDetail(orderId)
    this.setData({
      token: wx.getStorageSync('token')
    })
  },

  onShow(){
    this.setData({
      token: wx.getStorageSync('token')
    })
  },

  async getOrderInfoDetail(orderId){
    let orderRes = await queryOrderInfoDetail(orderId)
    if(orderRes.code === 200){
      this.setData({
        orderInfo: orderRes.data
      })
    }
  },

  async getProjectInstDetail(instId){
    // if(!this.checkIfExist(instId)){
    //   let proRes = await queryProjectInstDetail(instId)
    //   if(proRes.code === 200){
    //     let proInfo = proRes.data
    //     if(proInfo.itemJson){
    //       this.setData({
    //         inspectList: this.dealJson(JSON.parse(proInfo.itemJson))
    //       })
    //     }
    //   }
    // }
    let proRes = await queryProjectInstDetail(instId)
    if(proRes.code === 200){
      let proInfo = proRes.data
      if(proInfo.itemJson){
        this.setData({
          instInfo: proInfo,
          inspectList: this.dealJson(JSON.parse(proInfo.itemJson))
        })
      }
    }
  },

  checkIfExist(instId){
    const tempStorageOrder = wx.getStorageSync('tempStorageOrder')
    let res = false
    if(tempStorageOrder){
      const index = tempStorageOrder.findIndex(item => item.id == instId)
      if(index > -1){
        let currentItem = tempStorageOrder[index]
        let jsonList = JSON.parse(currentItem.itemJson)
        // this.dealJson(jsonList)
        this.setData({
          inspectList: this.dealJson(jsonList)
        })
        res = true
      }
    }
    return res
  },

  dealJson(dataList){
    let tempDataList = dataList
    tempDataList.forEach(item => {
      if(item.itemJson && typeof item.itemJson == 'string'){
        item.itemJson = JSON.parse(item.itemJson)
      }
    })
    return tempDataList
  },

  handlePhotoShoot(event){
    const field = event.currentTarget.dataset.field
    const inspectItem = event.currentTarget.dataset.inspectitem
    const currentItem = event.currentTarget.dataset.item
    let itemJson = typeof inspectItem.itemJson == 'string' ? JSON.parse(inspectItem.itemJson) : inspectItem.itemJson

    const _this = this
    wx.chooseMedia({
      count: 9,
      mediaType: ['image','video'],
      sourceType: ['album', 'camera'],
      maxDuration: 30,
      camera: 'back',
      success(res) {
        const fs = wx.getFileSystemManager()
        fs.readFile({
          filePath: res.tempFiles[0].tempFilePath,
          encoding: 'base64',
          success(readRes){
            uploadImg(readRes.data).then(picRes => {
              if(picRes.code === 200){
                currentItem[field] = picRes.msg
                itemJson.forEach(iten => {
                  if(iten.id === currentItem.id){
                    iten[field] = picRes.msg
                  }
                })
                _this.changePic(inspectItem, itemJson)
              }
            })
          } 
        })
      }
    })
  },

  changePic(newItem, itemJson){
    const newIndex = this.data.inspectList.findIndex(item => item.id === newItem.id)
    this.setData({
      [`inspectList[${newIndex}].itemJson`]: itemJson,
      [`inspectList[${newIndex}].updateTime`]: dayjs().format("YYYY-MM-DD HH:mm:ss"),
      [`instInfo.detectEndTime`]: dayjs().format("YYYY-MM-DD HH:mm:ss")
    })

    this.handleSaveAction()
  },

  stringifyJson(dataList){
    let tempDataList = dataList
    tempDataList.forEach(item => {
      if(item.itemJson && typeof item.itemJson != 'string'){
        item.itemJson = JSON.stringify(item.itemJson)
      }
    })
    return tempDataList
  },

  onChangeRes(val){
    const currentItem = val.currentTarget.dataset.currentitem
    const inspectItem = val.currentTarget.dataset.inspectitem
    const newIndex = this.data.inspectList.findIndex(item => item.id === inspectItem.id)
    let nowItem = this.data.inspectList[newIndex]
    let itemJsonList = typeof nowItem.itemJson == 'string' ? JSON.parse(nowItem.itemJson) : nowItem.itemJson
    itemJsonList.forEach(item => {
      if(item.id === currentItem.id ){
        item.checkRes = val.detail
      }
    })
    this.changePic(inspectItem, itemJsonList)
  },



  async handleSaveAction(){
    let tempList = []
    let channelInfo = {
      id: this.data.instId,
      itemJson: JSON.stringify( this.stringifyJson(this.data.inspectList)),
      detectEndTime: this.data.instInfo.detectEndTime
    }

    // detect_start_time
    if(!this.data.instInfo.detectStartTime){
      channelInfo.detectStartTime = dayjs().format("YYYY-MM-DD HH:mm:ss")
      this.setData({
        [`instInfo.detectStartTime`]: dayjs().format("YYYY-MM-DD HH:mm:ss")
      })
    }

    tempList.push(channelInfo)

    let saveRes = await inspectorSaveOrder(tempList)
    console.log("saveRes>>>", saveRes)
  },

  async handleUpdateInst(){
    let data = {
      id: this.data.instId,
      status: 3
    }
    let submitRes = await updateInstInfo(data)
    console.log("submitRes>>>", submitRes)
  },

  handleCheckIsOk(){
    let res = true
    let tempInspectList = this.dealJson(this.data.inspectList)
    for(let item of tempInspectList){
      if(item.isCollection == 'yes'){
        item.itemJson.forEach(iten => {
          if(!iten.pictureUrl){
            console.log("iten>>>1111>>>>",iten)
            res = false
          }
        })
      }else {
        item.itemJson.forEach(iten => {
          if(!iten.checkRes || (iten.isPhoto == 'yes' && iten.checkRes == 2 && !iten.pictureUrl1 && !iten.pictureUrl2) ){
            console.log("iten>>>2222>>>>",iten)
            res = false
          }
        })
      }
    }
    return res
  },

  confirmInfo(){
    // let checkIsOk = this.handleCheckIsOk()
    // console.log("checkIsOk>>>", checkIsOk)

    // if(checkIsOk){
    //   this.handleUpdateInst()
    // }

    this.handleUpdateInst()

    let channelInfo = {
      orderId: this.data.orderId
    }
    wx.navigateBack()
    const eventChannel = this.getOpenerEventChannel()
    eventChannel.emit("instItemChange", channelInfo)
  }
})